<!DOCTYPE html>
    <html lang="en">
<head>
    <title>双预防系统</title>
    <link rel="stylesheet" href="../../../assets/theme-chalk/index.css">
    <link rel="stylesheet" href="../../../style.css">
    <style>
        #allmap {
            width: 100%;
            height: 100%;
            overflow: hidden;
        }
        .page{
            width: 100%;
            height: 100%;
        }
        .toolbtn{
            position: absolute;
            top: 30px;
            left: 50px;
            z-index: 99;
        }
        .tooltipDiv{
            position: absolute;
            top: 100px;
            left: 50px;
            z-index: 99;
        }
        .square{
            border: 1px solid #fff;
            margin-top: 10px;
            font-size: 15px;
        }
        .anchorBL{display:none;}
    </style>
</head>
<body>
<div class="page" id="page-monitor">
    <div class="toolbtn">
        <el-button type="primary" @click="clearAll">清除所有区域</el-button>
        <el-button type="primary" @click="saveAll">保存所有区域</el-button>
        <el-button type="primary" icon="el-icon-refresh" @click="refresh">还原</el-button>
        <!--<el-button type="primary" @click="removeBuild">{{buildFlag?'隐藏建筑物':'显示建筑物'}}</el-button>-->
    </div>
    <div class="tooltipDiv">
        <div class="square" style="background:red">重大风险Ⅰ级</div>
        <div class="square" style="background:orange">较大风险Ⅱ级</div>
        <div class="square" style="background: yellow;">一般风险Ⅲ级</div>
        <div class="square" style="background: blue;">低风险Ⅳ级</div>
    </div>
    <div id="allmap" :style="{height:(height)+'px'}">
    </div>
    <el-dialog
            title="提示"
            :visible.sync="centerDialogVisible"
            width="65%">
        <el-form :inline="true" size="small"  :model="searchForm">
            <el-form-item label="区域" >
                <el-select v-model="searchForm.zoneId">
                    <el-option
                            v-for="item in zoneList"
                            :key="item.zone_id"
                            :label="item.zone_name"
                            :value="item.zone_id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="风险点等级" >
                <el-select style="width: 150px;" v-model="searchForm.grade">
                    <el-option label="Ⅰ" value="1"></el-option>
                    <el-option label="Ⅱ" value="2"></el-option>
                    <el-option label="Ⅲ" value="3"></el-option>
                    <el-option label="Ⅳ" value="4"></el-option>
                </el-select>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
    <el-button @click="centerDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="submitClick">确 定</el-button>
  </span>
    </el-dialog>
</div>


<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=GSkyZRDlTKcIqzerwITZvxee"></script>
<!--加载鼠标绘制工具-->
<script type="text/javascript" src="http://api.map.baidu.com/library/DrawingManager/1.4/src/DrawingManager_min.js"></script>
<link rel="stylesheet" href="http://api.map.baidu.com/library/DrawingManager/1.4/src/DrawingManager_min.css" />
<script type='text/javascript' src='../../../assets/bundle.js' charset='utf-8'></script>
<script type='text/javascript' src='../../../assets/jquery-1.11.2.min.js' charset='utf-8'></script>
<script type='text/javascript' src='../../../assets/echarts.min.js' charset='utf-8'></script>
<script type='text/javascript' src='../../../js/common.js' charset='utf-8'></script>
<script type='text/javascript' src='../../../js/component.js' charset='utf-8'></script>
<script>
    let mapLoading = null; // loading
    let vuePage = new Vue({
        el: '#page-monitor',
        data: {
            height:500,
            overlays :[],  //marker 数组
            map:null,    //地图
            centerDialogVisible:false,
            searchForm:{},
            zoneList:{},
            selMarker:{},  //选择marker
            dataJson:{},  //存数据
            labelJson:{},//存标签
            buildFlag:true,
        },
        created: function () {

        },
        methods: {
            removeBuild(){
                this.buildFlag = !this.buildFlag;
                if (this.buildFlag){
                    this.overlays = [];
                    this.MapCreated();
                    this.getMarkerList();
                }else {
                    this.map.setMapStyle({
                        styleJson:[
                            {
                                "featureType": "building",
                                "elementType": "labels",
                                "stylers": {
                                    "visibility": "off"
                                }
                            }
                        ]
                    })
                }
            },
            MapCreated(){
                this.map = null;
                let map = new BMap.Map('allmap',   {
                    enableMapClick: false
                });
                // map.setMapStyle(SiteConfig.mapStyle)
                // convertGCJ02ToBD09 中国正常GCJ02坐标---->百度地图BD09坐标
                let xpi = Math.PI*3000.0/180.0;
                let z = Math.sqrt(SiteConfig.account.lng * SiteConfig.account.lng + SiteConfig.account.lat * SiteConfig.account.lat) + 0.00002 * Math.sin(SiteConfig.account.lat * xpi);
                let theta = Math.atan2(SiteConfig.account.lat,SiteConfig.account.lng) + 0.000003 * Math.cos(SiteConfig.account.lng * xpi);
                let lng = z * Math.cos(theta) + 0.0065;
                let lat = z * Math.sin(theta) + 0.006;
                map.centerAndZoom(new BMap.Point(lng, lat), 24);
                map.enableScrollWheelZoom(true);
                map.setMapStyle({
                    styleJson:[
                        {
                            "featureType": "building",
                            "elementType": "labels",
                            "stylers": {
                                "visibility": "off"
                            }
                        }
                    ]
                });
                this.map = map;
                let styleOptions = {
                    strokeColor: "white", //边线颜色。
                    fillColor: "white", //填充颜色。当参数为空时，圆形将没有填充效果。
                    strokeWeight: 3, //边线的宽度，以像素为单位。
                    strokeOpacity: 0.8, //边线透明度，取值范围0 - 1。
                    fillOpacity: 0.6, //填充的透明度，取值范围0 - 1。
                    strokeStyle: 'solid' //边线的样式，solid或dashed。
                }
                //实例化鼠标绘制工具
                let drawingManager = new BMapLib.DrawingManager(map, {
                    isOpen: false, //是否开启绘制模式
                    enableDrawingTool: true, //是否显示工具栏
                    drawingToolOptions: {
                        anchor: BMAP_ANCHOR_TOP_RIGHT, //位置
                        offset: new BMap.Size(5, 5), //偏离值
                        scale: 0.8, //工具栏缩放比例
                        drawingModes: [BMAP_DRAWING_RECTANGLE], //设置只显示画矩形、圆的模式
                    },
                    rectangleOptions: styleOptions //矩形的样式
                });
                //添加鼠标绘制工具监听事件，用于获取绘制结果
                drawingManager.addEventListener('overlaycomplete', this.overlaycomplete);
            },
            refresh(){
              this.clearAll();
              this.getMarkerList();
            },
            clearAll(){
                this.map.clearOverlays();
                this.overlays = [];
                this.dataJson = {};
            },
            saveAll(){
                let param ={
                    projectNo: SiteConfig.account.projectNo,
                    zoneIds:'',
                    grades:'',
                    LatLng:'',
                }
                for (let key in this.dataJson){
                    param.zoneIds += this.dataJson[key].zoneId + '|';
                    param.grades += this.dataJson[key].grade + '|';
                    param.LatLng += this.dataJson[key].lat1 + ',' + this.dataJson[key].lat2 + ',' + this.dataJson[key].lat3 + ',' + this.dataJson[key].lat4 +  ',' + this.dataJson[key].lng1 + ','+ this.dataJson[key].lng2 + ','+  this.dataJson[key].lng3 + ',' +  this.dataJson[key].lng4 + '|';
                }
                if (param.zoneIds && param.grades && param.LatLng){
                    param.zoneIds = param.zoneIds.substr(0,param.zoneIds.length - 1);
                    param.grades = param.grades.substr(0,param.grades.length - 1);
                    param.LatLng = param.LatLng.substr(0,param.LatLng.length - 1);
                }
                console.log(param);
                HttpUtil.post('SceneForColor/Add',param).success((res)=>{
                    this.refresh();
                })
            },
            submitClick(){
                if (!(this.searchForm.zoneId && this.searchForm.grade)){
                    this.$message.warning('请选择区域和等级！');
                    return;
                }
                let point1 = this.getCenterPoint(this.selMarker.getPath());
                let text = '区域';
                for (item of this.zoneList){
                    if (item.zone_id == this.searchForm.zoneId){
                        text = item.zone_name;
                    }
                }
                let label = new BMap.Label(text, {
                    offset: new BMap.Size(-40, -25),
                    position: point1
                });
                if(this.labelJson[this.selMarker.indexId]){
                    this.map.removeOverlay(this.labelJson[this.selMarker.indexId]);
                }
                this.labelJson[this.selMarker.indexId] = label;
                this.map.addOverlay(label);
                switch (this.searchForm.grade) {
                    case  '1':
                        this.selMarker.setFillColor('red');
                        break;
                    case  '2':
                        this.selMarker.setFillColor('orange');
                        break;
                    case  '3':
                        this.selMarker.setFillColor('yellow');
                        break;
                    case  '4':
                        this.selMarker.setFillColor('blue');
                        break;
                }
                this.centerDialogVisible = false;
                this.dataJson[this.selMarker.indexId] ={
                    grade:this.searchForm.grade,
                    zoneId:this.searchForm.zoneId,
                    lat1:this.selMarker.getPath()[0].lat,
                    lng1:this.selMarker.getPath()[0].lng,
                    lat2:this.selMarker.getPath()[1].lat,
                    lng2:this.selMarker.getPath()[1].lng,
                    lat3:this.selMarker.getPath()[2].lat,
                    lng3:this.selMarker.getPath()[2].lng,
                    lat4:this.selMarker.getPath()[3].lat,
                    lng4:this.selMarker.getPath()[3].lng,
                };
            },
            selectMarker(e,ee,marker){
                this.centerDialogVisible = true;
                this.selMarker = marker;
            },
            removeMarker(e,ee,marker){
                this.map.removeOverlay(marker);
                if(this.labelJson[marker.indexId]){
                    this.map.removeOverlay(this.labelJson[marker.indexId]);
                }
                delete this.dataJson[marker.indexId];
            },
            overlaycomplete (e) {
                let result = "";
                result = "<p>";
                result += e.drawingMode + ":";
                if(e.drawingMode == BMAP_DRAWING_RECTANGLE) {
                    result += ' 所画的点个数：' + e.overlay.getPath().length;
                    result += '坐标分别为：';
                    if (e.overlay.getPath()[0].lng != e.overlay.getPath()[1].lng){
                        e.overlay.indexId = this.overlays.length;
                        this.overlays.push(e.overlay);
                    }else {
                        return;
                    }
                    for(let num = 0; num < e.overlay.getPath().length; num++) {
                        if (e.overlay.getPath()[0].lng != e.overlay.getPath()[1].lng)
                            result += e.overlay.getPath()[num].lng + ',' + e.overlay.getPath()[num].lat + '<br/>';
                    }
                }
                result += "</p>";
                console.log(result);

            },
            /**
             * 获取中心点，用于展示文字
             * @param path
             * @returns {BMap.Point}
             */
            getCenterPoint(path) {
                let x = 0.0;
                let y = 0.0;
                for(let i = 0; i < path.length; i++) {
                    x = x + parseFloat(path[i].lng);
                    y = y + parseFloat(path[i].lat);
                }
                x = x / path.length;
                y = y / path.length;
                return new BMap.Point(x, y);
            },
            /**
             * 点标注
             */
            getMarkerList(){
                this.loading();
              HttpUtil.get('SceneForColor/List',{projectNo:SiteConfig.account.projectNo}).success((res)=>{
                          let data  = res.data;
                          if (data.length>0){
                              for (let i = 0 ;i<data.length;i++){
                                  let color ='blue'
                                  switch (data[i].grade) {
                                      case  1:
                                          color = 'red';
                                          break;
                                      case  2:
                                          color ='orange';
                                          break;
                                      case  3:
                                          color = 'yellow';
                                          break;
                                      case  4:
                                          color = 'blue';
                                          break;
                                  }
                                  let rectangle = new BMap.Polygon([
                                      new BMap.Point(data[i].lng1, data[i].lat1),
                                      new BMap.Point(data[i].lng2, data[i].lat2),
                                      new BMap.Point(data[i].lng3, data[i].lat3),
                                      new BMap.Point(data[i].lng4, data[i].lat4),
                                  ], {
                                      strokeColor: "white",
                                      strokeWeight: 2,
                                      strokeOpacity: 0.5,
                                      fillColor: color,
                                  });
                                  rectangle.indexId = i;
                                  this.dataJson[i] ={
                                      grade:data[i].grade,
                                      zoneId:data[i].zoneId,
                                      lat1:data[i].lat1,
                                      lng1:data[i].lng1,
                                      lat2:data[i].lat2,
                                      lng2:data[i].lng2,
                                      lat3:data[i].lat3,
                                      lng3:data[i].lng3,
                                      lat4:data[i].lat4,
                                      lng4:data[i].lng4,
                                  };
                                  let point = this.getCenterPoint(rectangle.getPath());
                                  let label = new BMap.Label(data[i].zone_name, {
                                      offset: new BMap.Size(-40, -25),
                                      position: point
                                  });
                                  if(this.labelJson[i]){
                                      this.map.removeOverlay(this.labelJson[this.selMarker.indexId]);
                                  }
                                  this.labelJson[i] = label;
                                  let markerMenu = new BMap.ContextMenu();
                                  markerMenu.addItem(new BMap.MenuItem('删除', this.removeMarker.bind(rectangle)));
                                  markerMenu.addItem(new BMap.MenuItem('选择区域', this.selectMarker.bind( rectangle)));
                                  rectangle.addContextMenu(markerMenu);
                                  this.map.addOverlay(label);
                                  this.map.addOverlay(rectangle);
                                  this.overlays.push(rectangle);
                              }
                          }
                          this.closeLoading();
              })
            },
            loading() {
                mapLoading = this.$loading({
                    lock: true,
                    text: '数据加载中',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                });
            },
            closeLoading() {
                if (mapLoading)
                    mapLoading.close();
            },
        },
        watch:{
            overlays(val){
                if (val.length!=0){
                    this.map.removeOverlay(val[val.length-1]);
                    let markerMenu = new BMap.ContextMenu();
                    markerMenu.addItem(new BMap.MenuItem('删除', this.removeMarker.bind( val[val.length-1])));
                    markerMenu.addItem(new BMap.MenuItem('选择区域', this.selectMarker.bind( val[val.length-1])));
                    val[val.length-1].addContextMenu(markerMenu);
                    this.map.addOverlay(val[val.length-1]);
                }
            }
        },
        mounted: function () {
            this.overlays = [];
            this.MapCreated();
            this.getMarkerList();
            this.height = window.innerHeight;
            HttpUtil.get('Zone/List',{projectNo:SiteConfig.account.projectNo,pagesize:200}).success((res)=>{
                this.zoneList = res.data;
            });
        }
    });
</script>
</body>
</html>
